package com.jin.Es;

import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.Avg;
import org.elasticsearch.search.aggregations.metrics.AvgAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.List;

public class EsDemo05 {
    private RestHighLevelClient client;

    //1、创建SearchSourceBuilder对象
    private SearchSourceBuilder sourceBuilder;

    @Before
    public void init() {
        client = new RestHighLevelClient(RestClient.builder
                (new HttpHost("192.168.200.129", 9200, "http")));
    }

    @After
    public void close() {
        try {
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 文档聚合
     */
    @Test
    public void aggregations() throws IOException {

        sourceBuilder = new SearchSourceBuilder();

        SearchRequest searchRequest = new SearchRequest("user");

        TermsAggregationBuilder termsBuilder = AggregationBuilders.terms("terms_by_gender").field("gender");

        AvgAggregationBuilder avgBuilder = AggregationBuilders.avg("avg_by_age").field("age");

        termsBuilder.subAggregation(avgBuilder);
        sourceBuilder.aggregation(termsBuilder);

        SearchResponse search = client.search(searchRequest.source(sourceBuilder), RequestOptions.DEFAULT);

        //解析响应数据
        Aggregations aggregations = search.getAggregations();
        Terms termsRequest = aggregations.get("terms_by_gender");

        List<? extends Terms.Bucket> buckets = termsRequest.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            System.out.println("当前分桶的key="+bucket.getKeyAsString());
            System.out.println("当前分桶的文档数量="+bucket.getDocCount());

            //获得子聚合的结果
            Aggregations subAgg = bucket.getAggregations();
            Avg avg_by_age = subAgg.get("avg_by_age");
            System.out.println("平均值为="+avg_by_age.getValueAsString());
        }


    }
}
